# coding: UTF-8
# Filename : product.py
# Company : imedia
# Author : hui
# -*-coding:utf-8 -*-

from api.common.common import *
from api.common import mysql,log,utils,httputils,const,xml_tpl,err_tpl


#商品列表
def plist(request):
    httputils.footprint(request)
    
    cus_id = httputils.post(request, 'cus_id')
    size = httputils.post(request, 'size')
    pagenum = httputils.post(request, 'pagenum')
    
    if not utils.is_num(size): size = 5
    if not utils.is_num(pagenum): pagenum = 1
    if not utils.is_num(cus_id): cus_id = const.cus_id

    if validate(request):
        return validate(request)
    
    output = xml_tpl.imedia_start 
    output += make_pnodes(cus_id, size, pagenum)
    output += xml_tpl.imedia_end
    return response(output)

#商品详细
def pdetail(request, pid):
    httputils.footprint(request)

    if not utils.is_num(pid):
        return response(err_tpl.pid_not_number)

    if validate(request):
        return validate(request)

    output = xml_tpl.imedia_start 
    output += make_pnode(pid)
    output += xml_tpl.imedia_end
    return response(output)
    
#节点变量填充    
def node_var_fill(result):
    body_str = ''
    for obj in result:
        product_node = xml_tpl.product_node
        product_node = product_node.replace('{id}', str(obj[0]))
        product_node = product_node.replace('{name}', str(obj[1]))
        product_node = product_node.replace('{category}', str(obj[2]))
        product_node = product_node.replace('{image}', const.domain + str(obj[3]))
        product_node = product_node.replace('{storeinapp}', str(obj[4]))
        product_node = product_node.replace('{description}', str(obj[5]))
        body_str += product_node
    return body_str

#生成多行商品xml节点
def make_pnodes(cus_id, size, pagenum):
    sql = '''
    select p.id, p.name, c.class_name, p.images, p.store_in_app, p.description
    from chain_product as p left join p_class as c on p.category_id = c.id
    where p.active=1 and p.cus_id = %s
    limit %s, %s
    '''
    
    start_row = utils.get_star_row(size, pagenum)
    param = [int(cus_id), start_row, int(size)]
    result = mysql.doSearch(sql, param)
    return node_var_fill(result)

#生成单行商品xml节点
def make_pnode(pid):
    sql = '''
    select p.id, p.name, c.class_name, p.images, p.store_in_app, p.description
    from chain_product as p left join p_class as c on p.category_id = c.id
    where p.active=1 and p.id = %s
    limit 0, 1
    '''
    
    result = mysql.doSearch(sql, [int(pid)])
    return node_var_fill(result)
    
